package edu.yngsxy.dsstudyApi.core.ai.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 基于模型名称的AI响应解析器
 */
public class ModelResponseParser {
    private final ObjectMapper mapper;
    private final Map<String, String> modelPaths = Map.of(
            "openai", "/choices/0/message/content",
            "deepseek", "/choices/0/message/content",
            "gpt", "/choices/0/message/content",
            "doubao", "/result",
            "claude", "/content/0/text"
    );

    public ModelResponseParser(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    public String parse(String response, String model) {
        if (!StringUtils.hasText(response)) return "AI服务未返回有效答案";

        try {
            JsonNode json = mapper.readTree(response);

            // 尝试使用模型特定路径
            String path = modelPaths.get(model.toLowerCase());
            if (path != null) {
                JsonNode node = json.at(path);
                if (!node.isMissingNode() && node.isTextual()) return node.asText();
            }

            // 通用解析
            return parseGeneral(json);
        } catch (Exception e) {
            return response;
        }
    }

    private String parseGeneral(JsonNode json) {
        // 检查常见文本字段
        for (String field : new String[]{"text", "content", "message", "result", "response", "answer"}) {
            if (json.has(field) && json.get(field).isTextual()) {
                return json.get(field).asText();
            }
        }

        // 检查OpenAI格式
        if (json.has("choices") && json.get("choices").isArray() && !json.get("choices").isEmpty()) {
            JsonNode choice = json.get("choices").get(0);
            if (choice.has("message") && choice.get("message").has("content")) {
                return choice.get("message").get("content").asText();
            } else if (choice.has("text")) {
                return choice.get("text").asText();
            }
        }

        return json.toString();
    }
}

